package com.zpy.SmartChargeStation.mqtt.client.factory;

import com.zpy.SmartChargeStation.mqtt.client.conf.MqttProps;
import com.zpy.SmartChargeStation.mqtt.client.model.MqttConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * description: 主题订阅
 */

@Configuration
@EnableIntegration
@Slf4j
public class InBoundSubscribe {

    @Resource
    private MqttProps props;

    @Resource
    private MqttPahoClientFactory factory;

    //消息处理
    @Resource
    private InBoundMessageRev messageRev;


    /**
     * description: 接收通道
     */
    @Bean(name = MqttConstants.In_CHANNEL)
    public MessageChannel inChannel() {

        return new DirectChannel();
    }

    /**
     * description: 订阅主题的适配器
     */
    @Bean
    public MessageProducer getAdapter() {

        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        props.getClientId(),
                        factory,
                        props.getTopic()
                );
        // 添加对 statTopic 的订阅
        adapter.addTopic(props.getStatTopic(), 0);
        //设置转换器
        adapter.setConverter(new DefaultPahoMessageConverter());
        //设置订阅通道
        adapter.setOutputChannel(inChannel());

        log.info(">>>>>工厂模式订阅主题适配器生成状态 "+adapter.toString());

        return adapter;
    }

    /**
     * description: 接收消息的处理
     */
    @Bean
    @ServiceActivator(inputChannel = MqttConstants.In_CHANNEL)
    public MessageHandler inHandler(){

        return this.messageRev;

    }

}
